package com.theta.gateway.infra.common.utils;

import org.springframework.cglib.beans.BeanCopier;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 对象拷贝工具类
 *
 * @author theta
 */
public class BeanCopierUtils {

    private static final int DEFAULT_INITIAL_CAPACITY = 100;
    private static Map<String, BeanCopier> beanCopierMap = new ConcurrentHashMap<>(DEFAULT_INITIAL_CAPACITY);

    /**
     * copy对象
     *
     * @param source
     * @param target
     */
    public static void copyProperties(Object source, Object target) {
        String beanKey = generateKey(source.getClass(), target.getClass());
        BeanCopier copier;
        if (!beanCopierMap.containsKey(beanKey)) {
            copier = BeanCopier.create(source.getClass(), target.getClass(), false);
            beanCopierMap.put(beanKey, copier);
        } else {
            copier = beanCopierMap.get(beanKey);
        }
        copier.copy(source, target, null);
    }

    /**
     * set to list
     *
     * @param set
     */
    public static <T> List<T> copySet2List(Set<T> set) {
        List list = new ArrayList();
        if (CollectionUtils.isEmpty(set)) {
            return list;
        }
        for (T obj : set) {
            list.add(obj);
        }
        return list;
    }

    private static String generateKey(Class<?> class1, Class<?> class2) {
        return class1.toString() + class2.toString();
    }
}
